<template>
  <div class="wrapper">
    <div class="add-wrapper" v-if="uploadedImage.length < 10">
      <form ref="form" class="form">
        <input class="file" ref="file" type="file" accept="image/*" @change="onFileChanged">
        <img class="add" src="@/assets/backgroundhome/add_pic.svg">
      </form>
    </div>
    <img
      class="image"
      v-for="(item, index) in uploadedImage"
      :key="index"
      :src="`data:image/jpeg;base64,${item}`"
      @click="removeUploaded(index)"
    >
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "img_upload",
  data() {
    return {
      id: "",
      uploadedImage: []
    };
  },
  mounted() {
    this.selectid();
  },
  methods: {
    actions(index) {},
    onFileChanged() {
      const file = this.$refs.file.files[0];
      if (!file) return;
      const formData = new FormData();
      formData.set("image", file);
      axios({
        method: "post",
        url: "/upload",
        data: formData,
        headers: {
          id: this.id
        }
      }).then(({ data }) => {
        this.uploadedImage.push(data);
      });
    },
    removeUploaded(index) {
      axios
        .delete(`/upload/${index}`, {
          headers: {
            id: this.id
          }
        })
        .then(r => {
          this.uploadedImage.splice(index, 1);
        });
    },
    selectid() {
      axios.get("/upload/id").then(({ data }) => {
        this.id = data;
        let apiUpload = {
          id: data
        };
        this.$store.commit("setapiUpload", apiUpload);
      });
    }
  }
};
</script>
<style scoped>
.image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  display: inline-block;
  line-height: 80px;
  margin: 0 4px 0 0px;
}
.form {
  display: inline-block;
  position: relative;
  height: 80px;
  width: 80px;
}
.file {
  opacity: 0;
  width: 80px;
  height: 80px;
  z-index: 3;
  position: relative;
  display: inline-block;
  left: 0;
  top: 0;
}
.add {
  width: 80px;
  height: 80px;
  display: block;
  margin-top: -80px;
}
.add-wrapper {
  width: 80px;
  height: 80px;
  float: left;
  margin-right: 4px;
}
.wrapper {
  min-height: 80px;
}
</style>
